/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.bullionxpress.client.application;

import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.SwingUtilities;
import com.bullionxpress.shared.listeners.AccountEvent;
import com.bullionxpress.shared.listeners.AccountListener;
import com.bullionxpress.shared.model.Instrument;
import com.bullionxpress.shared.model.Quote;
import com.bullionxpress.shared.model.Tick;
import com.bullionxpress.shared.service.AccountDatabase;
import com.bullionxpress.shared.service.QuoteService;
import com.bullionxpress.shared.util.Log;
import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.SwingWorker;

/**
 *
 * @author BullionXpress.com
 */
public class ClientManager {

    ArrayList listeners = new ArrayList();
    Timer timer = new Timer();
    TimerTask task = null;
    TimerTask quoteTask = null;
    final Object objLock = new Object();
    Lock lock = new ReentrantLock();

    public ClientManager() {
        task = new TimerTask() {

            public void run() {
                try {
                    AccountDatabase db = ClientGlobals.accountDatabase;
                    if (ClientGlobals.user != null) {
                        ClientGlobals.account = db.get(ClientGlobals.account.getId());
                        final AccountEvent ae = new AccountEvent();
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                Thread t = new Thread() {
                                    public void run() {
                                        dispatch(ae);
                                    }
                                };
                                t.setPriority(Thread.MIN_PRIORITY);
                                t.start();
                            }
                        });
                    }
                    System.out.print(".");
                } catch (Exception ex) {
                    Log.info(ex);
                }
            }
        };
        quoteTask = new TimerTask() {

            public void run() {
                try {
                    QuoteService qm = ClientGlobals.quoteService;

                    Quote q = qm.getQuote(ClientGlobals.instrument);
                    final Tick tick = new Tick();
                    tick.setInstrument(ClientGlobals.instrument);
                    tick.setHigh(q.getAsk());
                    tick.setOpen(q.getAsk());
                    tick.setClose(q.getBid());
                    tick.setLow(q.getBid());
                    tick.setTimestamp(System.currentTimeMillis());
                    Log.info("Add tick");
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            ClientGlobals.chartView.add(tick);
                        }
                    });
                    Log.info("Tick Added");
                    Log.info(tick.toString());
                } catch (Exception ex) {
                    Log.info(ex);
                }
            }
        };



    }

    public void schedule() {
        timer.scheduleAtFixedRate(task, 0, 3000);
        timer.scheduleAtFixedRate(quoteTask, 0, 60000);
    }

    public void addAccountListener(AccountListener al) {
        try {
            lock.lock();
            synchronized (objLock) {
                listeners.add(al);
            }
        } catch (Exception ex) {
           } finally {
            lock.unlock();
        }
    }

    public void removeAccountListener(AccountListener al) {
        try {
            lock.lock();
            synchronized (objLock) {
                listeners.remove(al);
            }
        } catch (Exception ex) {
           } finally {
            lock.unlock();
        }
    }

    public void dispatch(AccountEvent ae) {
        try {
            lock.lock();
            synchronized (objLock) {
                try {
                    Iterator i = listeners.iterator();
                    while (i.hasNext()) {
                        try {
                            AccountListener al = (AccountListener) i.next();
                            al.update(ae);
                        } catch (Exception ex) {
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch(Exception ex) {

        } finally {
            lock.unlock();
        }
    }
}
